import type { IcStatus, ORDERSTATUS, PACKAGESTATUS, QUERYORDERSTATUS, SHOPORDERSTATUS } from '@/pluginPackage/order/orderList/types'
import type { ApiOrder, ShopOrder } from '@/pluginPackage/order/orderList/types'

export const UPLOAD_URL = import.meta.env.VITE_BASE_URL + import.meta.env.VITE_UPLOAD_URI
type OptionalStatus = keyof typeof ORDERSTATUS | keyof typeof SHOPORDERSTATUS | keyof typeof PACKAGESTATUS
// 订单详情图标配置
export const orderDetailIconConfig = {
  待支付: 'icon-a-Frame7',
  待发货: 'icon-a-Frame8',
  待收货: 'icon-a-Frame9',
  交易成功: 'icon-jiaoyichenggong',
  待评价: 'icon-jiaoyichenggong',
  已关闭: 'icon-a-Frame11',
  已完成: 'icon-a-Frame10',
  拼团中: 'icon-zhangdan',
  拼团失败: 'icon-jiaoyichenggong',
  待接单: 'icon-shenhezhong',
  待到店: 'icon-shanghugenjin',
  待取货: 'icon-daiquhuo',
  配送中: 'icon-peisongguanli',
  已送达: 'icon-qianshou-',
  配送异常: 'icon-yichang',
} as const
const queryStatus: Record<keyof typeof QUERYORDERSTATUS, string> = {
  UNPAID: '待付款',
  UN_DELIVERY: '待发货',
  UN_RECEIVE: '待收货',
  COMPLETED: '已完成',
  UN_COMMENT: '待评价',
  CLOSED: '已关闭',
}
const orderStatus: Record<keyof typeof ORDERSTATUS, string> = {
  UNPAID: '等待买家付款',
  PAID: '已支付',
  BUYER_CLOSED: '已关闭',
  SYSTEM_CLOSED: '已关闭',
  SELLER_CLOSED: '已关闭',
  TEAMING: '拼团中',
  TEAM_FAIL: '拼团失败',
}
const shopOrderStatus: Record<keyof typeof SHOPORDERSTATUS, string> = {
  OK: '正常状态',
  SYSTEM_CLOSED: '已关闭',
  BUYER_CLOSED: '已关闭',
  SELLER_CLOSED: '已关闭',
}
const packageStatus: Record<keyof typeof PACKAGESTATUS, string> = {
  WAITING_FOR_DELIVER: '待发货',
  WAITING_FOR_RECEIVE: '待收货',
  BUYER_WAITING_FOR_COMMENT: '待评价',
  SYSTEM_WAITING_FOR_COMMENT: '待评价',
  BUYER_COMMENTED_COMPLETED: '已完成',
  SYSTEM_COMMENTED_COMPLETED: '已完成',
}

interface OrderDetailsConfig {
  isShowAfsBtn: boolean
  isShowFooterBtn: boolean
  isShowFooterRightBtnText: string
  isShowModifyAddressBtn: boolean
}

/**
 * 订单详情状态页面配置
 * @param {*} order
 */
export const getOrderDetailsConfig = (order: ApiOrder) => {
  const orderDetailsConfig = {
    isShowAfsBtn: false,
    isShowFooterBtn: true,
    isShowFooterRightBtnText: '',
    isShowModifyAddressBtn: false,
  }
  if (order.status === 'UNPAID') return unpaid(orderDetailsConfig)
  // 拼团判断
  if (['TEAM'].includes(order.type) && order.status !== 'TEAM_FAIL') {
    const newOrderDetailsConfig = shopOrdersOk(order.shopOrders[0], orderDetailsConfig)
    newOrderDetailsConfig.isShowFooterBtn = true
    newOrderDetailsConfig.isShowFooterRightBtnText = '我的拼团'
    return newOrderDetailsConfig
  }
  if (order.shopOrders[0].status === 'OK') return shopOrdersOk(order.shopOrders[0], orderDetailsConfig)
  return orderDetailsConfig
}
const unpaid = (orderDetailsConfig: OrderDetailsConfig) => {
  orderDetailsConfig.isShowAfsBtn = false
  orderDetailsConfig.isShowFooterRightBtnText = '立即付款'
  return orderDetailsConfig
}
const shopOrdersOk = (shopOrders: ShopOrder, orderDetailsConfig: OrderDetailsConfig) => {
  const okNum = shopOrders.shopOrderItems.filter((orderItem) => orderItem.status === 'OK').length
  if (okNum === shopOrders.shopOrderItems.length) {
    // 所有的订单状态都是'OK' 查看包状态
    return pagesStatus(shopOrders, orderDetailsConfig)
  }
  // 订单状态不一致分开处理
  handledSeparately(shopOrders, orderDetailsConfig)
  return orderDetailsConfig
}
// * @param NONE 无售后
// * @param REFUND_REQUEST 申请退款
// * @param SYSTEM_REFUND_AGREE 系统自动同意退款申请
// * @param REFUND_AGREE 已同意退款申请
// * @param REFUND_REJECT 拒绝了退款申请
// * @param REFUNDED 退款已到账
// * @param RETURN_REFUND_REQUEST 申请退货退款
// * @param SYSTEM_RETURN_REFUND_AGREE 系统自动同意退货退款申请
// * @param RETURN_REFUND_AGREE 已同意退货退款申请
// * @param RETURN_REFUND_REJECT 拒绝了退货退款申请
// * @param SYSTEM_RETURNED_REFUND_CONFIRM 退货退款 系统自动确认收货
// * @param RETURNED_REFUND   退货已发出
// * @param SYSTEM_CLOSED 系统自动关闭
// * @param RETURNED_REFUND_CONFIRM 确认退货已收到
// * @param RETURNED_REFUND_REJECT 已拒绝收货
// * @param  RETURNED_REFUNDED 退货退款已完成
// * @param  BUYER_CLOSED  主动撤销了售后申请
const handledSeparately = (shopOrders: ShopOrder, orderDetailsConfig: OrderDetailsConfig) => {
  // 此订单处于关闭状态 说明退款了 需要展示退款成功按钮
  orderDetailsConfig.isShowAfsBtn = true
}
const pagesStatus = (shopOrders: ShopOrder, orderDetailsConfig: OrderDetailsConfig) => {
  const len = shopOrders.shopOrderItems.length
  // sendGoodsNum 找出待发货的订单个数
  const sendGoodsNum = shopOrders.shopOrderItems.filter((orderItem) => orderItem.packageStatus === 'WAITING_FOR_DELIVER').length
  if (sendGoodsNum === len) {
    orderDetailsConfig.isShowModifyAddressBtn = true
    orderDetailsConfig.isShowAfsBtn = true
    orderDetailsConfig.isShowFooterRightBtnText = ''
    return orderDetailsConfig
  }

  return sendGoodsNumNext(shopOrders, orderDetailsConfig)
}
// 已发货
const sendGoodsNumNext = (shopOrders: ShopOrder, orderDetailsConfig: OrderDetailsConfig) => {
  const confirmGoods = shopOrders.shopOrderItems.some((orderItem) => orderItem.packageStatus === 'WAITING_FOR_RECEIVE')

  if (confirmGoods) {
    orderDetailsConfig.isShowAfsBtn = true
    orderDetailsConfig.isShowFooterRightBtnText = '确认收货'
    return orderDetailsConfig
  }
  const comment = shopOrders.shopOrderItems.some((orderItem) => orderItem.packageStatus === 'BUYER_WAITING_FOR_COMMENT')
  const commentSystem = shopOrders.shopOrderItems.some((orderItem) => orderItem.packageStatus === 'SYSTEM_WAITING_FOR_COMMENT')
  if (comment || commentSystem) {
    orderDetailsConfig.isShowFooterRightBtnText = '评价'
    orderDetailsConfig.isShowAfsBtn = true
    return orderDetailsConfig
  }
  // 已完成
  return completed(shopOrders, orderDetailsConfig)
}
const completed = (shopOrders: ShopOrder, orderDetailsConfig: OrderDetailsConfig) => {
  const isCompleted = shopOrders.shopOrderItems.some((orderItem) => orderItem.packageStatus === 'BUYER_COMMENTED_COMPLETED')
  const isCompletedSystem = shopOrders.shopOrderItems.some((orderItem) => orderItem.packageStatus === 'SYSTEM_COMMENTED_COMPLETED')
  if (isCompleted || isCompletedSystem) {
    orderDetailsConfig.isShowFooterBtn = false
    orderDetailsConfig.isShowFooterRightBtnText = ''
    orderDetailsConfig.isShowAfsBtn = false
    return orderDetailsConfig
  }

  orderDetailsConfig.isShowFooterBtn = false
  orderDetailsConfig.isShowFooterRightBtnText = ''
  orderDetailsConfig.isShowAfsBtn = false
  return orderDetailsConfig
}

/**
 * 如果是等待付款就展示付款按钮
 * @param {OptionalStatus} status
 */
export const isUnpaidOrder = (status: OptionalStatus) => {
  return ['UNPAID'].includes(status)
}
/**
 * 未付款订单状态改中文
 * @param {keyof} str
 */

const getOrdercn = (str: keyof typeof ORDERSTATUS) => {
  return orderStatus[str]
}
// 拼团判断 展示我的拼团按钮
const isTeam = (order: ApiOrder) => {
  return ['TEAM'].includes(order.type) && order.status !== 'TEAM_FAIL' && order.status !== 'UNPAID'
}
/**
 * 是否支付订单
 * @param {OptionalStatus} status 订单下所有状态
 */
const isPayOrder = (status: OptionalStatus) => {
  return !['UNPAID'].includes(status)
}
/**
 * 是否待收货
 * @param {OptionalStatus} status 订单下所有状态
 */
const isReceive = (status: OptionalStatus) => {
  return ['WAITING_FOR_RECEIVE', 'BUYER_COMMENTED_COMPLETED'].includes(status)
}

/**
 * 是否已完成
 * @param {OptionalStatus} status 订单下所有状态
 */
const isCompleted = (status: OptionalStatus) => {
  return ['BUYER_COMMENTED_COMPLETED', 'SYSTEM_COMMENTED_COMPLETED'].includes(status)
}
/**
 * 是否待评价
 * @param {OptionalStatus} status 订单下所有状态
 */
const isComment = (status: OptionalStatus) => {
  return ['BUYER_WAITING_FOR_COMMENT', 'SYSTEM_WAITING_FOR_COMMENT'].includes(status)
}
/**
 * 关闭订单 展示删除订单按钮
 * @param {OptionalStatus} status 订单下所有状态
 */
const isCloseOrder = (status: OptionalStatus) => {
  return ['BUYER_CLOSED', 'SYSTEM_CLOSED', 'SELLER_CLOSED'].includes(status)
}
export { queryStatus, orderStatus, shopOrderStatus, packageStatus, getOrdercn, isPayOrder, isCloseOrder, isReceive, isTeam, isComment, isCompleted }

/**
 * 订单状态 超级版
 */
export interface OrderStatusPlus {
  //订单状态 描述
  desc: string
  //是否已关闭
  isClosed: boolean
  //关闭时间
  closeTime?: string
}

export enum OrderStatusZh {
  WAITING_FOR_DELIVER = '待发货',
  WAITING_FOR_RECEIVE = '待收货',
  WAITING_FOR_DELIVER_PART = '待发货 (部分发货)',
  COMMENTED_COMPLETED = '已完成',
  WAITING_FOR_COMMENT = '待评价',
}

/**
 * 根据订单详情 获取订单状态
 */
export const getOrderDetailStatusPlus = (order?: ApiOrder, shopId?: Long): OrderStatusPlus => {
  if (!order) return { desc: '', isClosed: false }
  //未支付只需要检查总订单状态
  if (order.status !== 'PAID') {
    const statusPlus = OrderStatusPlusHandler[order.status]
    statusPlus.closeTime = order.updateTime
    return statusPlus
  }
  const shopOrders = order.shopOrders
  let shopOrder = shopOrders[0]
  if (shopId && shopId !== shopOrder.shopId) {
    for (let i = 1; i < shopOrders.length; i++) {
      const current = shopOrders[i]
      if (current && shopId === current.shopId) {
        shopOrder = current
        break
      }
    }
  }
  return orderStatusPlus(shopOrder, order)
  //已支付 订单已拆分显示 只需要取第一条店铺订单数据
}

export function orderStatusPlus(shopOrder: ShopOrder, order?: ApiOrder, showIc = true): OrderStatusPlus {
  const statusPlus: OrderStatusPlus = {
    desc: '已关闭',
    isClosed: true, // 是否展示评价按钮
  }
  if (order?.shopOrders?.[0]?.status !== 'OK') {
    return statusPlus
  }
  console.log('订单详情', order)
  // 如果传进来了order 则判断是否是同城配送订单
  if (order && order.icStatus && order.extra?.distributionMode && showIc) {
    statusPlus.desc = IcStatus[order.icStatus]
    statusPlus.isClosed = order.icStatus !== 'DELIVERED'
    const shopOrderItems = shopOrder.shopOrderItems
    if (order.icStatus === 'ERROR') {
      for (let i = 0; i < shopOrderItems.length; i++) {
        const shopOrderItem = shopOrderItems[i]
        if (shopOrderItem.status === 'OK' && shopOrderItem.packageStatus === 'WAITING_FOR_DELIVER' && shopOrderItem.sellType !== 'CONSIGNMENT') {
          statusPlus.desc = IcStatus['PRICE_PADDING']
        }
      }
    } else if (order.icStatus === 'DELIVERED') {
      // 拿到所有的包裹状态
      const mergeStatus = shopOrderItems.map((item) => item.packageStatus)
      /**
       * packageStatus:
       * WAITING_FOR_DELIVER: '待发货',
       * WAITING_FOR_RECEIVE: '待收货',
       * BUYER_WAITING_FOR_COMMENT: '待评价',
       * SYSTEM_WAITING_FOR_COMMENT: '待评价',
       * BUYER_COMMENTED_COMPLETED: '已完成',
       * SYSTEM_COMMENTED_COMPLETED: '已完成',
       */
      if (mergeStatus.includes('WAITING_FOR_DELIVER')) {
        statusPlus.desc = '待发货'
      }
      if (mergeStatus.includes('WAITING_FOR_RECEIVE')) {
        statusPlus.desc = '待收货'
      }
      // 有一个待评价就待评价
      if (mergeStatus.includes('BUYER_WAITING_FOR_COMMENT') || mergeStatus.includes('SYSTEM_WAITING_FOR_COMMENT')) {
        statusPlus.desc = '待评价'
      }
      // 有一个已完成就已完成
      if (mergeStatus.includes('BUYER_COMMENTED_COMPLETED') || mergeStatus.includes('SYSTEM_COMMENTED_COMPLETED')) {
        statusPlus.desc = '已完成'
      }
    }
    return statusPlus
  }
  if (shopOrder.status !== 'OK') {
    const statusPlus = ShopOrderStatusPlusHandler[shopOrder.status]
    statusPlus.closeTime = shopOrder.updateTime
    return statusPlus
  }
  const shopOrderItems = shopOrder.shopOrderItems

  //检查是否全部关闭
  const deliverConfig = {
    deliverNum: 0,
    unDeliverNum: 0,
    okNum: 0,
    // 已评价
    evaluation: 0,
  }
  for (let shopOrderItem of shopOrderItems) {
    if (shopOrderItem.status === 'OK') {
      deliverConfig.okNum += 1
      deliverConfig.unDeliverNum += shopOrderItem.packageStatus === 'WAITING_FOR_DELIVER' ? 1 : 0
      deliverConfig.deliverNum += shopOrderItem.packageStatus === 'WAITING_FOR_RECEIVE' ? 1 : 0
      deliverConfig.evaluation += ['BUYER_COMMENTED_COMPLETED', 'SYSTEM_COMMENTED_COMPLETED'].includes(shopOrderItem.packageStatus) ? 1 : 0
    }

    const currentCloseTime = statusPlus.closeTime
    const closeTime = shopOrderItem.updateTime
    if (!closeTime) {
      continue
    }
    statusPlus.closeTime = !currentCloseTime ? closeTime : closeTime > currentCloseTime ? closeTime : currentCloseTime
  }
  const { unDeliverNum, evaluation, deliverNum, okNum } = deliverConfig
  if (okNum) {
    const deliverConfigTotal = deliverNum + unDeliverNum
    statusPlus.isClosed = false
    statusPlus.desc =
      unDeliverNum === okNum
        ? OrderStatusZh.WAITING_FOR_DELIVER
        : deliverNum === okNum
        ? OrderStatusZh.WAITING_FOR_RECEIVE
        : deliverConfigTotal === okNum
        ? OrderStatusZh.WAITING_FOR_DELIVER_PART
        : evaluation === okNum
        ? OrderStatusZh.COMMENTED_COMPLETED
        : OrderStatusZh.WAITING_FOR_COMMENT
  }
  return statusPlus
}

/**
 *     OK: '正常状态',
 *     SYSTEM_CLOSED: '系统关闭',
 *     BUYER_CLOSED: '买家关闭订单',
 *     SELLER_CLOSED: '卖家关闭订单',
 */
export const ShopOrderStatusPlusHandler: Record<keyof typeof SHOPORDERSTATUS, OrderStatusPlus> = {
  OK: {
    desc: '正常状态',
    isClosed: false,
  },
  SYSTEM_CLOSED: {
    desc: '已关闭',
    isClosed: true,
  },
  BUYER_CLOSED: {
    desc: '已关闭',
    isClosed: true,
  },
  SELLER_CLOSED: {
    desc: '已关闭',
    isClosed: true,
  },
}
/**
 * UNPAID: '等待买家付款',
 * PAID: '已支付',
 * BUYER_CLOSED: '买家关闭订单',
 * SYSTEM_CLOSED: '系统关闭订单',
 * SELLER_CLOSED: '卖家关闭订单',
 */
export const OrderStatusPlusHandler: Record<keyof typeof ORDERSTATUS, OrderStatusPlus> = {
  UNPAID: {
    desc: '待支付',
    isClosed: false,
  },
  PAID: {
    desc: '待发货',
    isClosed: false,
  },
  BUYER_CLOSED: {
    desc: '已关闭',
    isClosed: true,
  },
  SYSTEM_CLOSED: {
    desc: '已关闭',
    isClosed: true,
  },
  SELLER_CLOSED: {
    desc: '已关闭',
    isClosed: true,
  },
  TEAMING: {
    desc: '拼团中',
    isClosed: false,
  },
  TEAM_FAIL: {
    desc: '拼团失败',
    isClosed: true,
  },
}
